using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using TextSupport;

namespace WorldPad
{
	public partial class MainForm : Form, IEditSurface
	{
		Font _defaultFont = new Font("Courier New", 10);
		TextFrame _textFrame;
		TextFrameController _textController;
		TextFrameView _textView;

		public MainForm()
		{
			InitializeComponent();
		}

		#region IEditSurface Members

		public RectangleF GetExtent()
		{
			return ClientRectangle;
		}

		Graphics TextSupport.IEditSurface.GetGraphics()
		{
			return Graphics.FromHwnd(Handle);
		}

		public Font GetDefaultFont()
		{
			return _defaultFont;
		}

		void TextSupport.IEditSurface.Invalidate(RectangleF rect)
		{
			base.Invalidate(new Rectangle((int)rect.Left, (int)rect.Top, (int)rect.Right, (int)rect.Bottom));
		}

		#endregion

		private void MainForm_Load(object sender, EventArgs e)
		{
			OnFileNew();
		}

		void OnFileNew()
		{
			_textFrame = new TextFrame();
			_textView = new TextFrameView(_textFrame, this);
			_textController = new TextFrameController(_textFrame, _textView);

			_textController.SetText("using");
			_textController.BeginEdit();
		}

		protected override void OnPaint(PaintEventArgs e)
		{
			_textView.Paint(e.Graphics);
		}

		private void MainForm_SizeChanged(object sender, EventArgs e)
		{
			if (Width > 0)
			{
				_textController.UpdateLayout();
				UpdateScrollBars();
			}
		}

		void UpdateScrollBars()
		{
			if (_textFrame.Extent.Height > Height)
			{
				VerticalScroll.Enabled = true;
				VerticalScroll.Minimum = 0;
				VerticalScroll.Maximum = (int)_textFrame.Extent.Height - Height;
				VerticalScroll.LargeChange = Height;
				VerticalScroll.Value = 0;
			}
			else
			{
				VerticalScroll.Enabled = false;
			}
		}

		private void MainForm_KeyPress(object sender, KeyPressEventArgs e)
		{
			e.Handled = _textController.KeyPress(e.KeyChar);
		}

		private void MainForm_KeyDown(object sender, KeyEventArgs e)
		{
			e.Handled = _textController.KeyDown(e);
		}

		private void MainForm_KeyUp(object sender, KeyEventArgs e)
		{
			e.Handled = _textController.KeyUp(e);
		}

		private void caretTimer_Tick(object sender, EventArgs e)
		{
			_textController.CaretTimerTick();
		}

		#region IEditSurface Members

		public void RestartCaretTimer()
		{
			caretTimer.Stop();
			caretTimer.Start();
		}

		#endregion
}
}